package com.wnhz.work.yz.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.text.Selection;
import android.text.Spannable;
import android.util.LruCache;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.AllocationBean;
import com.wnhz.work.yz.bean.BathRoomSkuBean;
import com.wnhz.work.yz.constant.Constants;
import com.wnhz.work.yz.utils.BroadCastReceiverUtil;
import com.wnhz.work.yz.utils.CalculateUtil;
import com.wnhz.work.yz.utils.LogUtil;
import com.wnhz.work.yz.utils.MyUtils;
import com.wnhz.work.yz.utils.NetworkUtil;
import com.wnhz.work.yz.utils.Prefer;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by admin on 2017/1/14.
 */
public class BashRoomAdapter extends BaseAdapter implements AbsListView.OnScrollListener {

    private Context context;
    private List<BathRoomSkuBean.InfoEntity> dataList;
    private ListView my_listView;
    private int position;
    private String money;
    int chooseNum = 0;
    int deleteNum = 0;

    public BashRoomAdapter(Context context, List<BathRoomSkuBean.InfoEntity> dataList, ListView my_listView ,String money) {
        this.context = context;
        this.dataList = dataList;
        this.money = money;
        this.my_listView = my_listView;
        taskCollection = new HashSet<BitmapWorkerTask>();
        // 获取应用程序最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;
        // 设置图片缓存大小为程序最大可用内存的1/8
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount();
            }
        };
        this.my_listView.setOnScrollListener(this);
    }

    //外层列表的index
    public void setPosition(int position){
        this.position = position;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        AllocationViewHolder viewHolder = null;
        if (convertView == null) {
            viewHolder = new AllocationViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_bathroom_list, null);
            viewHolder.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
            viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            viewHolder.tv_store = (TextView) convertView.findViewById(R.id.tv_store);
            viewHolder.tv_type = (TextView) convertView.findViewById(R.id.tv_type);
            viewHolder.now_price = (TextView) convertView.findViewById(R.id.now_price);
            viewHolder.tv_des = (TextView) convertView.findViewById(R.id.tv_des);
            viewHolder.original_price = (TextView) convertView.findViewById(R.id.original_price);
            viewHolder.tv_number = (TextView) convertView.findViewById(R.id.tv_number);
            viewHolder.ll_item = (LinearLayout) convertView.findViewById(R.id.ll_item);

            viewHolder.reduce = (ImageView) convertView.findViewById(R.id.reduce);
            viewHolder.ll_add = (ImageView) convertView.findViewById(R.id.ll_add);
            viewHolder.shopping_number = (TextView) convertView.findViewById(R.id.shopping_number);//购物车个数

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (AllocationViewHolder) convertView.getTag();
        }

        if ("1".equals(dataList.get(position).getCan_buy())){
            viewHolder.now_price.setText("¥" + (Double.parseDouble(money) + Double.parseDouble(dataList.get(position).getAdd_price())));
            viewHolder.original_price.setText("原价¥" + (Double.parseDouble(dataList.get(position).getPrice())
                    + Double.parseDouble(dataList.get(position).getAdd_price())));
        }else {//0
            viewHolder.now_price.setText("¥" + dataList.get(position).getOprice());
            viewHolder.original_price.setText("原价¥" + dataList.get(position).getOprice());
        }

        viewHolder.original_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        viewHolder.shopping_number.setText(""+ dataList.get(position).getChooseNum());
        viewHolder.tv_des.setText(dataList.get(position).getSku_info());
//        viewHolder.iv_img.setTag(dataList.get(position).getGoods_pic());
        Glide.with(context).load(dataList.get(position).getImg()).error(R.mipmap.img_chanpinfenlei1).crossFade().into(viewHolder.iv_img);
//        ImageLoader.getInstance().displayImage(dataList.get(position).getGoods_pic(),viewHolder.iv_img);
//        setImageView(dataList.get(position).getGoods_pic(), viewHolder.iv_img);

        viewHolder.tv_name.setText(dataList.get(position).getName());

        viewHolder.tv_type.setText(dataList.get(position).getLabel());
        viewHolder.tv_store.setText("库存：" + dataList.get(position).getStore() + Prefer.getInstance().getTest());


        final AllocationViewHolder finalViewHolder = viewHolder;
        final Map<Integer,String> pricemap = new HashMap<>();
        viewHolder.ll_add.setTag(viewHolder.shopping_number);

        viewHolder.ll_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(NetworkUtil.isNetworkAvailable(context)) {
                    chooseNum = dataList.get(position).getChooseNum();
                    if (chooseNum < Integer.parseInt(dataList.get(position).getStore())) {
                        chooseNum++;
                        dataList.get(position).setChooseNum(chooseNum);
                    }
                        Intent intent = new Intent();
                        intent.putExtra("position", BashRoomAdapter.this.position);
                        intent.putExtra("bean", dataList.get(position));
                        intent.setAction(Constants.UPDATE_PRICE);
                        BroadCastReceiverUtil.sendBroadcastByIntent(context, intent);
                        int tt = (int) Prefer.getInstance().getTest() + 1;
                }else {
                    Toast.makeText(context,"网络不可用，请检查网络",Toast.LENGTH_SHORT).show();
                }

            }
        });
        viewHolder.reduce.setTag(viewHolder.shopping_number);

        viewHolder.reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                BroadCastReceiverUtil.sendBroadcast(context, Constants2.UPDATE_FIRST_PRICE);
            if(NetworkUtil.isNetworkAvailable(context)){

                chooseNum = dataList.get(position).getChooseNum();
                    TextView textView = (TextView) v.getTag();
                    int nums = 1;
                    if(chooseNum > 0){


                    if(chooseNum == 1){
                            Toast.makeText(context, "再减就没了", Toast.LENGTH_SHORT).show();
                    }else{
                        chooseNum--;
                        dataList.get(position).setChooseNum(chooseNum);
                        Intent intent= new Intent();
                        intent.putExtra("max_position",BashRoomAdapter.this.position);
                        intent.putExtra("position",position);
                        intent.putExtra("bean", dataList.get(position));
                        intent.setAction(Constants.UPDATE_PRICE);
                        BroadCastReceiverUtil.sendBroadcastByIntent(context,intent);
                    }
                    }



            }else {
    Toast.makeText(context,"网络不可用，请检查网络",Toast.LENGTH_SHORT).show();
}
            }
        });
        final BashRoomAdapter.AllocationViewHolder allocationViewHolder = viewHolder;
        viewHolder.shopping_number.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (NetworkUtil.isNetworkAvailable(context)) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    View view = View.inflate(context, R.layout.dialog_edit, null);
                    TextView queding1 = (TextView) view.findViewById(R.id.queding1);
                    TextView quxaio1 = (TextView) view.findViewById(R.id.quxiao1);
                    final EditText shopping_number = (EditText) view.findViewById(R.id.shopping_number);
               /*     if (MyUtils.isBiggerTwo(Double.parseDouble(dataList.get(position).getName()))) {
                        shopping_number.setText("" + MyUtils.doubleRound(Double.parseDouble(dataList.get(position).getStore())));
                    } else {
                        shopping_number.setText("" + Double.parseDouble(dataList.get(position).getStore()));
                    }*/

//                shopping_number.setText("" + Double.parseDouble(dataList.get(position).getGoods_nums()));
//                    MyApplication.getInstance().setYsnum(Double.parseDouble(shopping_number.getText().toString()));
                    shopping_number.postInvalidate();
                    //切换后将EditText光标置于末尾
                    CharSequence charSequence = shopping_number.getText();
                    if (charSequence instanceof Spannable) {
                        Spannable spanText = (Spannable) charSequence;
                        Selection.setSelection(spanText, charSequence.length());
                    }

                    builder.setView(view);
                    final AlertDialog show = builder.show();
                    Window dialogWindow = show.getWindow();
                    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                    dialogWindow.setGravity(Gravity.CENTER);
                    dialogWindow.setAttributes(lp);
                    queding1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                        BroadCastReceiverUtil.sendBroadcast(context, Constants2.UPDATE_FIRST_PRICE);

                            if (shopping_number.getText().toString().equals("")) {
                                Toast.makeText(context, "数量不能为空", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            if (Integer.parseInt(shopping_number.getText().toString()) == 0) {
                                Toast.makeText(context, "数量不能小于0.0", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if(NetworkUtil.isNetworkAvailable(context)){
//                            MyApplication.getInstance().setPackagePrice_GoodsPrice(dataList.get(position).getPrice());
                            int nums = Integer.parseInt(shopping_number.getText().toString());
                            if (nums < 1) {
                                nums = 1;
                            } else {
                                nums = nums;
                            }

//                            MyApplication.getInstance().setInputnums(nums);
                            dataList.get(position).setChooseNum(nums );


                    /*        AllocationBean allocationBean = new AllocationBean();
                            allocationBean.setGoods_nums(nums + "");
                            allocationBean.setPosition(position);*/

                            allocationViewHolder.shopping_number.setText(nums + "");
                            Intent intent = new Intent();
                            intent.putExtra("max_position", BashRoomAdapter.this.position);
                            intent.putExtra("position", position);
                            intent.putExtra("bean", dataList.get(position));
                            intent.setAction(Constants.UPDATE_PRICE);
                            BroadCastReceiverUtil.sendBroadcastByIntent(context, intent);
                            show.dismiss();
                        }else {
                                Toast.makeText(context,"网络不可用，请检查网络",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    quxaio1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            show.dismiss();
                        }
                    });

                }else {
                    Toast.makeText(context,"网络不可用，请检查网络",Toast.LENGTH_SHORT).show();
                }
            }

        });

        return convertView;
    }

    class AllocationViewHolder {
        ImageView iv_img, reduce, ll_add;;
        TextView tv_name, shopping_number,tv_store,tv_des;
        TextView tv_type,now_price,original_price;
        TextView tv_price;
        LinearLayout ll_item;
        TextView tv_number;
    }

    /**
     * 记录所有正在下载或等待下载的任务。
     */
    private Set<BitmapWorkerTask> taskCollection;

    /**
     * 图片缓存技术的核心类，用于缓存所有下载好的图片，在程序内存达到设定值时会将最少最近使用的图片移除掉。
     */
    private LruCache<String, Bitmap> mMemoryCache;

    /**
     * GridView的实例
     */

    /**
     * 第一张可见图片的下标
     */
    private int mFirstVisibleItem;

    /**
     * 一屏有多少张图片可见
     */
    private int mVisibleItemCount;

    /**
     * 记录是否刚打开程序，用于解决进入程序不滚动屏幕，不会下载图片的问题。
     */
    private boolean isFirstEnter = true;

    /**
     * 给ImageView设置图片。首先从LruCache中取出图片的缓存，设置到ImageView上。如果LruCache中没有该图片的缓存，
     * 就给ImageView设置一张默认图片。
     *
     * @param imageUrl  图片的URL地址，用于作为LruCache的键。
     * @param imageView 用于显示图片的控件。
     */
    private void setImageView(String imageUrl, ImageView imageView) {
        //    Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);
        Bitmap bitmap = ImageLoader.getInstance().loadImageSync(imageUrl);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
//            imageView.setImageResource(R.mipmap.img_chanpinfenlei1);
        }
    }

    /**
     * 将一张图片存储到LruCache中。
     *
     * @param key    LruCache的键，这里传入图片的URL地址。
     * @param bitmap LruCache的键，这里传入从网络上下载的Bitmap对象。
     */
    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemoryCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    /**
     * 从LruCache中获取一张图片，如果不存在就返回null。
     *
     * @param key LruCache的键，这里传入图片的URL地址。
     * @return 对应传入键的Bitmap对象，或者null。
     */
    public Bitmap getBitmapFromMemoryCache(String key) {
        return mMemoryCache.get(key);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // 仅当GridView静止时才去下载图片，GridView滑动时取消所有正在下载的任务
        if (scrollState == SCROLL_STATE_IDLE) {
            loadBitmaps(mFirstVisibleItem, mVisibleItemCount);
        } else {
            cancelAllTasks();
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                         int totalItemCount) {
        mFirstVisibleItem = firstVisibleItem;
        mVisibleItemCount = visibleItemCount;
        // 下载的任务应该由onScrollStateChanged里调用，但首次进入程序时onScrollStateChanged并不会调用，
        // 因此在这里为首次进入程序开启下载任务。
        if (isFirstEnter && visibleItemCount > 0) {
            loadBitmaps(firstVisibleItem, visibleItemCount);
            isFirstEnter = false;
        }
    }

    /**
     * 加载Bitmap对象。此方法会在LruCache中检查所有屏幕中可见的ImageView的Bitmap对象，
     * 如果发现任何一个ImageView的Bitmap对象不在缓存中，就会开启异步线程去下载图片。
     *
     * @param firstVisibleItem 第一个可见的ImageView的下标
     * @param visibleItemCount 屏幕中总共可见的元素数
     */
    private void loadBitmaps(int firstVisibleItem, int visibleItemCount) {
        try {
            for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) {
                String imageUrl = dataList.get(i).getImg();
                Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);
                if (bitmap == null) {
                    BitmapWorkerTask task = new BitmapWorkerTask();
                    taskCollection.add(task);
                    task.execute(imageUrl);
                } else {
                    ImageView imageView = (ImageView) my_listView.findViewWithTag(imageUrl);
                    if (imageView != null && bitmap != null) {
                        imageView.setImageBitmap(bitmap);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消所有正在下载或等待下载的任务。
     */
    public void cancelAllTasks() {
        if (taskCollection != null) {
            for (BitmapWorkerTask task : taskCollection) {
                task.cancel(false);
            }
        }
    }

    /**
     * 异步下载图片的任务。
     *
     * @author guolin
     */
    class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {

        /**
         * 图片的URL地址
         */
        private String imageUrl;

        @Override
        protected Bitmap doInBackground(String... params) {
            imageUrl = params[0];
            // 在后台开始下载图片
            Bitmap bitmap = downloadBitmap(params[0]);
            if (bitmap != null) {
                // 图片下载完成后缓存到LrcCache中
                addBitmapToMemoryCache(params[0], bitmap);
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            // 根据Tag找到相应的ImageView控件，将下载好的图片显示出来。
            ImageView imageView = (ImageView) my_listView.findViewWithTag(imageUrl);
            if (imageView != null && bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
            taskCollection.remove(this);
        }

        /**
         * 建立HTTP请求，并获取Bitmap对象。
         *
         * @param imageUrl 图片的URL地址
         * @return 解析后的Bitmap对象
         */
        private Bitmap downloadBitmap(String imageUrl) {
            Bitmap bitmap = null;
            HttpURLConnection con = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                con.setDoInput(true);
                con.setDoOutput(true);
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (Exception e) {
                // e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }
            return bitmap;
        }

    }


}
